package com.example.enginsdk;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;

import java.io.File;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 应用程序相关操作
 * Date:2017/12/6
 * I'm glad to share my knowledge with you all.
 *
 * @author Gaolei
 */
public class AppUtils {

    private static String IME_PACKAGE = "com.csizg.imemodule.service.PinyinIME";

    /**
     * 获得当前所在进程的进程名<br>
     */
    public synchronized static String getCurrentProcessName(Context cxt) {
        ActivityManager actMgr = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        if (actMgr == null) {
            return null;
        }
        List<RunningAppProcessInfo> runningAppProcesses = actMgr.getRunningAppProcesses();
        if (runningAppProcesses == null) {
            return null;
        }
        int pid = android.os.Process.myPid();
        for (RunningAppProcessInfo appProcess : runningAppProcesses) {
            if (appProcess != null && appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    /**
     * 获取版本名
     */
    public static String getVersionName(Context context) {
        String name = "";
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            name = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return name;
    }

    /**
     * 获取版本号
     */
    public static int getVersionCode(Context context) {
        int code = 0;
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            code = info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 检查是否勾选了输入法
     */
    public static boolean checkHasCheck(Context context) {
        boolean isInList = false;
        try {
            List<InputMethodInfo> methodInfos = ((InputMethodManager)(context.getSystemService(Context.INPUT_METHOD_SERVICE))).getEnabledInputMethodList();
            for (InputMethodInfo info : methodInfos) {
                if (info.getId().contains(IME_PACKAGE)){
                    isInList = true;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isInList;
    }


    /**
     * 检查是否是默认输入法
     *
     * @return 是否是默认输入法
     */
    public static boolean checkIsDefault(Context context) {
        boolean isDefault = false;
        try {
            String curInputMethod = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
            //密信不包含输入法
            if (IME_PACKAGE.equals(curInputMethod)) {
                isDefault = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isDefault;
    }

    /**
     * 打开勾选输入法界面
     */
    public static void  startChooseInput(Context context) {
        Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
        context.startActivity(intent);
    }

    /**
     * 打开设置默认输入法弹窗
     */
    public static void  startSetDefaultInput(Context context) {
        ((InputMethodManager)(context.getSystemService(Context.INPUT_METHOD_SERVICE))).showInputMethodPicker();
    }

    /**
     * 跳转到指定应用的google play的详情页<br>
     */
    public static void openGooglePlay(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return;
        }
        openGooglePlay(context, "market://details?id=" + packageName,
            "https://play.google.com/store/apps/details?id=" + packageName);
    }

    /**
     * 跳转到google play, 优先跳转到客户端，若失败尝试跳转到网页
     *
     * @param uriString 用于跳转客户端的uri字符串
     * @param urlString 用于跳转到网页版的url字符串
     */
    private static void openGooglePlay(Context context, String uriString, String urlString) {
        boolean isOk = false;
        if (!TextUtils.isEmpty(uriString)) {
            // 先尝试打开客户端
            isOk = openActivitySafely(context, uriString, "com.android.vending");
            if (!isOk) {
                isOk = openActivitySafely(context, uriString, null);
            }
        }
        if (!isOk) {
            if (!TextUtils.isEmpty(urlString)) {
                // 试试打开浏览器
                openActivitySafely(context, urlString, null);
            }
        }
    }

    /**
     * 安全地打开外部的activity
     *
     * @param packageName 可选，明确要跳转的程序的包名
     * @return 是否成功
     */
    private static boolean openActivitySafely(Context context, String uri, String packageName) {
        boolean isOk = true;
        try {
            Uri uriData = Uri.parse(uri);
            final Intent intent = new Intent(Intent.ACTION_VIEW, uriData);
            if (!TextUtils.isEmpty(packageName)) {
                intent.setPackage(packageName);
            }
            if (!(context instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            context.startActivity(intent);
        } catch (Throwable e) {
            e.printStackTrace();
            isOk = false;
        }
        return isOk;
    }


    /**
     * 根据包名判断应用是否安装
     *
     * @param context     上下文
     * @param packageName 包名
     * @return 结果
     */
    public static boolean isAppInstalled(Context context, String packageName) {
        boolean isExist = false;
        PackageManager pm = context.getPackageManager();
        ApplicationInfo applicationInfo = null;
        try {
            applicationInfo = pm.getApplicationInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (null != applicationInfo) {
            isExist = true;
        }

        return isExist;
    }
}
